<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Log;
class Index extends Controller
{
	public function index()
	{
		$this->headfoot();
		return $this->fetch('index');
	}
	public function weibo()
	{
		$data = DB::query('select * from weibo where created_at !=? order by created_at desc',['']);
		foreach($data as $k=>$v)
		{
			if(empty($v['created_at']))
			{
				unset($data[$k]);
			}
			$data[$k]['created_at'] = date('Y-m-d H:i:s',intval($v['created_at']));
		}
		$this->assign('list',$data);
		$this->headfoot();
		return $this->fetch('weibo_list');
	}
	public function auth()
	{
		include_once( EXTEND_PATH.'weibo/config.php' );
		include_once( EXTEND_PATH.'weibo/saetv2.ex.class.php' );
		$o = new \weibo\SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
		$this->assign('code_url', $code_url);
        	return $this->fetch('weibo_index');
	}
	public function callback()
	{
		$this->headfoot();
		include_once( EXTEND_PATH.'weibo/config.php' );
		include_once( EXTEND_PATH.'weibo/saetv2.ex.class.php' );
		$o = new \weibo\SaeTOAuthV2( WB_AKEY , WB_SKEY );
		$token = '';
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
			}
		}
		if ($token) {
			$_SESSION['token'] = $token;
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
			$auth_time = DB::query('select id from settings where name=?',['auth_time']);
			if(empty($auth_time))
			{
				DB::execute('insert into settings (name,time)values (?,?)',['auth_time',time()]);
			}
			else
			{
				DB::execute('update settings set time=? where name=?',[time(),'auth_time']);
			}
			
			echo "授权完成,<a href='/'>正在进入你的微博列表页面</a><br/>";
			$this->index();
		}
		else
		{
			echo '授权失败。';
		}
	}
	public function headfoot()
	{
		if(!isset($_SESSION))
		{
			session_start();
		}
		$name = 'HuangRui';
		DB::query("
			 CREATE TABLE IF NOT EXISTS `settings` (
			   `id` int(11) NOT NULL AUTO_INCREMENT,
			   `name` varchar(32) NOT NULL,
			   `time` int(11) NOT NULL,
			   PRIMARY KEY (`id`)
			 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;");
		
		$auth_time = DB::query('select time from settings where name=?',['auth_time']);
		$auth_status = !empty($auth_time) &&(time() - $auth_time[0]['time']<7*86400) ? 1 : 0;
		$this->assign('auth_status',$auth_status);
		$this->assign('screen_name',$name);
		$this->assign('webroot',WEBROOT);
		$this->assign('static_path',WEBROOT.'/static/');
		$head = $this->fetch('head');
		$foot = $this->fetch('foot');
		$this->assign('head',$head);
		$this->assign('foot',$foot);
	}
}
